<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="12">
          <a-form-item label="区域类型" v-bind="validateInfos.regionType">
            <j-dict-select-tag v-model:value="formData.regionType" dictCode="regionType" placeholder="请选择区域类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="仓库编码" v-bind="validateInfos.number">
            <a-input v-model:value="formData.number" placeholder="请输入仓库编码" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="仓库名称" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入仓库名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所在位置" v-bind="validateInfos.position">
            <a-input v-model:value="formData.position" placeholder="请输入所在位置" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="占地面积（㎡）" v-bind="validateInfos.floorSpace">
            <a-input v-model:value="formData.floorSpace" placeholder="请输入占地面积（㎡）" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="仓库管理员" v-bind="validateInfos.manager">
            <a-input v-model:value="formData.manager" placeholder="请输入仓库管理员" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系方式" v-bind="validateInfos.tel">
            <a-input v-model:value="formData.tel" placeholder="请输入联系方式" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="有无防火墙" v-bind="validateInfos.isFirewall">
            <j-dict-select-tag type='radio' v-model:value="formData.isFirewall" dictCode="haveOrNot" placeholder="请选择有无防火墙" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="仓库用途" v-bind="validateInfos.warehouseUse">
	          <j-dict-select-tag v-model:value="formData.warehouseUse" dictCode="warehouseUse" placeholder="请选择仓库用途" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="存放物体形态" v-bind="validateInfos.mediumForm">
	          <j-dict-select-tag v-model:value="formData.mediumForm" dictCode="mediumForm" placeholder="请选择存放物体形态" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="设计使用年限" v-bind="validateInfos.ageLimit">
	          <a-input-number v-model:value="formData.ageLimit" placeholder="请输入设计使用年限" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="火灾危险等级" v-bind="validateInfos.fireGrade">
	          <j-dict-select-tag v-model:value="formData.fireGrade" dictCode="fireDangerGrade" placeholder="请选择火灾危险等级" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" v-bind="validateInfos.status">
            <j-dict-select-tag type='radio' v-model:value="formData.status" dictCode="normalOrStop" placeholder="请选择状态" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="租户id" v-bind="validateInfos.tenantId">
            <a-input v-model:value="formData.tenantId" placeholder="请输入租户id" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col> -->
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="仓库产品" key="tbBasicsStashProduct" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tbBasicsStashProductTableRef"
          :loading="tbBasicsStashProductTable.loading"
          :columns="tbBasicsStashProductTable.columns"
          :dataSource="tbBasicsStashProductTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryTbBasicsStashProductListByMainId, queryDataById, saveOrUpdate } from '../TbBasicsStash.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {tbBasicsStashProductColumns} from '../TbBasicsStash.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "TbBasicsStashForm",
    components:{
      JDictSelectTag,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const tbBasicsStashProductTableRef = ref();
      const tbBasicsStashProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: tbBasicsStashProductColumns,
        dataSource: []
      });
      const activeKey = ref('tbBasicsStashProduct');
      const formData = reactive<Record<string, any>>({
        id: '',
        regionType: '',   
        number: '',   
        name: '',   
        position: '',   
        floorSpace: '',   
        manager: '',   
        tel: '',   
        isFirewall: '',   
        warehouseUse: '',   
        mediumForm: '',   
        ageLimit: undefined,
        fireGrade: '',   
        status: '',   
        tenantId: '',   
      });

      //表单验证
      const validatorRules = reactive({
        regionType: [{ required: true, message: '请输入区域类型!'},],
        number: [{ required: true, message: '请输入仓库编码!'},],
        name: [{ required: true, message: '请输入仓库名称!'},],
        position: [{ required: true, message: '请输入所在位置!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        tbBasicsStashProductTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const tbBasicsStashProductDataList = await queryTbBasicsStashProductListByMainId(row['id']);
        tbBasicsStashProductTable.dataSource = [...tbBasicsStashProductDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'tbBasicsStashProduct': tbBasicsStashProductTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        tbBasicsStashProductTableRef,
        tbBasicsStashProductTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>
